package gpl.scotlandyard.detective.hint.main;

import gpl.androidcommons.service.MapLoaderPerformer;
import gpl.androidcommons.service.ScheduleServiceListener;
import gpl.scotlandyard.beans.basics.Node;
import gpl.scotlandyard.detective.hint.R;
import gpl.scotlandyard.utils.Scotlandyard;

import java.util.List;

import android.app.AlertDialog;
import android.os.Bundle;
import android.support.v4.app.FragmentActivity;
import android.support.v4.view.ViewPager;
import android.util.Log;
import android.view.Menu;

public class MainActivity extends FragmentActivity implements ScheduleServiceListener<List<Node>> {

  private static final String TAG = MainActivity.class.toString();

  /** If this becomes too memory
   * intensive, it may be best to switch to a
   * {@link android.support.v4.app.FragmentStatePagerAdapter}.
   */
  private MainSectionPagerAdapter pagerAdapter;

  private ViewPager viewPager;

  private List<Node> boardMap;

  @Override
  protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.main_activity);
    new MapLoaderPerformer(getAssets(), Scotlandyard.Config.MAP_FILE, this).run();
    pagerAdapter = new MainSectionPagerAdapter(getSupportFragmentManager(), this);
    viewPager = (ViewPager) findViewById(R.id.pager);
    viewPager.setAdapter(pagerAdapter);
  }

  @Override
  public boolean onCreateOptionsMenu(Menu menu) {
    getMenuInflater().inflate(R.menu.main, menu);
    return true;
  }

  @Override
  public void done(final List<Node> result) {
    final MainActivity activity = this;
    runOnUiThread(new Runnable() {
      @Override
      public void run() {
        Log.i(TAG, "job finished");
        activity.boardMap = result;
      }
    });
  }

  @Override
  public void failed(final Exception e) {
    final MainActivity activity = this;
    runOnUiThread(new Runnable() {
      @Override
      public void run() {
        Log.e(TAG, "impossible to load map : " + e.getLocalizedMessage());
        new AlertDialog.Builder(activity).setMessage(R.string.service_loading_board).create().show();
        Log.e(TAG, "stop application");
        finish();
      }
    });
  }

  List<Node> getBoardMap() {
    return boardMap;
  }
}
